package com.xin.data.simbapesa.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaExitActivityBinding;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.OrderUtils;
import com.xin.data.simbapesa.utils.PopUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.ViewUtils;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class SimbaExitActivity extends BaseActivity<SimbaExitActivityBinding> {


    int time;

    private final int TIME_WHAT = 1;

    TextView tvOk;


    @Override
    protected SimbaExitActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaExitActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
            }
        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P163, "");
            showLogOUt();
        });
        binding.tvDelete.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P162, "");
            int state = OrderUtils.getOrderStatus();
            LogUtil.e("me", "state->" + state);
            if (state <= 0 || state > 5 || state == 2) {
                time = 10;
                showDeleteUser();
                mHandler.sendEmptyMessageDelayed(TIME_WHAT, 1000);
            } else {
                Toast.makeText(getActivity(), ResUtils.s(R.string.delete_hit), Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P159;
        UP_TYPE2 = PU.P160;

        int radius = getResources().getDimensionPixelSize(R.dimen.dp_14);
        Glide.with(this)
                .load(R.mipmap.logo)
                .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL)))
                .into(binding.tvIcon);

        String androidVersion = BaseParams.getVersionName(this);
        binding.tvVer.setText(ResUtils.s(R.string.ver_title, androidVersion));

    }

    @Override
    protected void onResume() {
        super.onResume();
        dropUserData("GET");
    }

    @SuppressLint("HandlerLeak")
    final
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_WHAT) {
                mHandler.removeMessages(TIME_WHAT);
                time = time - 1;
                if (time > 0) {
                    showDeleteUser();
                    mHandler.sendEmptyMessageDelayed(TIME_WHAT, 1000);
                } else {
                    showDeleteUser();
                }
            }
        }
    };

    void showDeleteUser() {
        String okStr;
        if (time > 0) {
            okStr = ResUtils.s(R.string.delete_btn) + "(" + time + ")";
        } else {
            okStr = ResUtils.s(R.string.delete_btn);
        }
        if (tvOk == null) {
            tvOk = PopUtils.showDeleteUserPop(getActivity(), binding.getRoot(), (title, value, position, index) -> {
                if (title.equals("0")) {
                    tvOk.setText(ResUtils.s(R.string.delete_btn));
                    tvOk.setSelected(false);
                } else {
                    dropUserData("DROP");
                }
                mHandler.removeMessages(TIME_WHAT);
                tvOk = null;
            });
        }
        tvOk.setText(okStr);
        tvOk.setSelected(time <= 0);
    }

    void showLogOUt() {
        exit();
    }

    void dropUserData(String type) {
        showLoading("");
        String token = SpUtils.get_string(this, SpUtils.KEY_TOKEN, "");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[89], U.URL_MAIN_PRODUCT, token);
        json.addProperty("type", type);


        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-dropUserData post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "dropUserData json->" + json1);
                            if (type.equalsIgnoreCase("GET")) {
                                String showDropButton = JsonParse.dropUserDataJson2Obj(json1);
                                if (!TextUtils.isEmpty(showDropButton)) {
                                    if (showDropButton.equals("YES")) {
                                        binding.tvDelete.setVisibility(View.VISIBLE);
                                    } else {
                                        binding.tvDelete.setVisibility(View.INVISIBLE);
                                    }
                                }
                            } else {
                                if (JsonParse.getCode(json1)) {
                                    exit();
                                } else {
                                    showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    void exit() {
        SpUtils.save_string(getActivity(), SpUtils.KEY_PHONE, "");
        SpUtils.save_string(getActivity(), SpUtils.KEY_USERID, "");
        SpUtils.save_string(getActivity(), SpUtils.KEY_TOKEN, "");
        SpUtils.save_int(getActivity(), SpUtils.KEY_SCORE_NUM, 0);
        Intent intent = new Intent(getActivity(), SimbaLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        SimbaApp.getInstance().clearActivity();
        finish();
    }


}
